package com.ruoyi.sso.service.impl;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.sso.domain.SsoWxToken;
import com.ruoyi.sso.domain.SsoWxUser;
import com.ruoyi.sso.domain.SsoWyUrl;
import com.ruoyi.sso.mapper.SsoWxTokenMapper;
import com.ruoyi.sso.mapper.SsoWxUserMapper;
import com.ruoyi.sso.mapper.SsoWyUrlMapper;
import com.ruoyi.sso.service.ISsoWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * sso微信用户Service业务层处理
 *
 * @author zsj
 * @date 2020-01-07
 */
@Service
public class SsoWxUserServiceImpl implements ISsoWxUserService {
    @Autowired
    private SsoWxUserMapper ssoWxUserMapper;

    @Autowired
    private SsoWyUrlMapper ssoWyUrlMapper;

    @Autowired
    private SsoWxTokenMapper ssoWxTokenMapper;

    @Autowired
    private SsoWyUrlMapper wyUrlMapper;

    /**
     * 查询sso微信用户
     *
     * @param wxUserId sso微信用户ID
     * @return sso微信用户
     */
    @Override
    public SsoWxUser selectSsoWxUserById(Long wxUserId) {
        return ssoWxUserMapper.selectSsoWxUserById(wxUserId);
    }

    /**
     * 查询sso微信用户列表
     *
     * @param ssoWxUser sso微信用户
     * @return sso微信用户
     */
    @Override
    public List<SsoWxUser> selectSsoWxUserList(SsoWxUser ssoWxUser) {
        return ssoWxUserMapper.selectSsoWxUserList(ssoWxUser);
    }

    /**
     * 新增sso微信用户
     *
     * @param ssoWxUser sso微信用户
     * @return 结果
     */
    @Override
    public int insertSsoWxUser(SsoWxUser ssoWxUser) {
        return ssoWxUserMapper.insertSsoWxUser(ssoWxUser);
    }

    /**
     * 修改sso微信用户
     *
     * @param ssoWxUser sso微信用户
     * @return 结果
     */
    @Override
    public int updateSsoWxUser(SsoWxUser ssoWxUser) {
        return ssoWxUserMapper.updateSsoWxUser(ssoWxUser);
    }

    /**
     * 删除sso微信用户对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteSsoWxUserByIds(String ids) {
        return ssoWxUserMapper.deleteSsoWxUserByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除sso微信用户信息
     *
     * @param wxUserId sso微信用户ID
     * @return 结果
     */
    @Override
    public int deleteSsoWxUserById(Long wxUserId) {
        return ssoWxUserMapper.deleteSsoWxUserById(wxUserId);
    }

    @Override
    public SsoWxUser queryByOpenId(String openId) {

        return ssoWxUserMapper.queryByOpenId(openId);
    }

    /**
     * 绑定信息
     *
     * @param phone   手机号码
     * @param cardnum 身份证后6位
     * @param ids     物业id
     * @param token   用户token
     * @param role    角色0业主1物管
     */
    @Override
    public Map<String, Object> binding(String phone, String cardnum, String ids, String token, String role) {

        Map<String, Object> res = new HashMap<String, Object>();

        String url1 = "/estateOwnerInfo/checkForWx";
        String url2 = "/operInf/add";
        String url3 = "/estateOwnerInfo/detail";

        String[] id = ids.split(",");
        String binding = "";// 服务url对应的id
        String ownerIds = "";// 业主id
        String errConnect = "";
        List<SsoWyUrl> urls = new LinkedList<SsoWyUrl>();// 匹配到的服务url
        for (String s : id) {
            if (StrUtil.isNotBlank(s)) {
                SsoWyUrl selectSsoWyUrlById = ssoWyUrlMapper.selectSsoWyUrlById(Long.parseLong(s));
                // 通过接口校验业主信息
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("phone", phone);
                params.put("certificatesNo", cardnum);

                try {
                    String post = HttpUtil.post(selectSsoWyUrlById.getUrl() + url1, params, 3000);
                    if (StrUtil.isNotBlank(post) && !post.contains("Error")) {
                        JSONObject result = JSONObject.parseObject(post);
                        // Map<String, Object> result = JSON.parseObject(post);
                        if (result.get("data") != null) {

                            List<Map> owner = JSONObject.parseArray(result.get("data").toString(), Map.class);

                            if (StrUtil.isBlank(binding) && StrUtil.isBlank(ownerIds)) {

                                ownerIds += owner.get(0).get("id");
                            } else {
                                ownerIds += ",";
                                ownerIds += owner.get(0).get("id");
                            }
                            urls.add(selectSsoWyUrlById);
                        }
                    }

                } catch (IORuntimeException e) {
                    errConnect += selectSsoWyUrlById.getDescription() + ",";

                    continue;
                } catch (HttpException e) {
                    errConnect += selectSsoWyUrlById.getDescription() + "服务未启动,";

                    continue;
                }

            }
        }
        if (StrUtil.isNotBlank(errConnect)) {
            res.put("exception", errConnect + "连接超时");
        }

        if (StrUtil.isBlank(ownerIds)) {
            res.put("code", 1);
            res.put("msg", "手机号码或身份证错误");
            return res;
        } else {
            // 绑定信息
            SsoWxToken queryByToken = ssoWxTokenMapper.queryByToken(token);
            SsoWxUser ssoWxUser = ssoWxUserMapper.selectSsoWxUserById(queryByToken.getUserId());
            SsoWxUser user = new SsoWxUser();
            user.setWxUserId(queryByToken.getUserId());
            user.setRole(StrUtil.isNotBlank(role) ? Integer.parseInt(role) : 0);


            String[] ownerIdsStr = ownerIds.split(",");
            String errMsg = "";
            String msg = "";
            for (int i = 0; i < ownerIdsStr.length; i++) {
                // 通过接口获取业主信息
                Map<String, Object> params1 = new HashMap<String, Object>();
                params1.put("id", ownerIdsStr[i]);
                String url = urls.get(i).getUrl() + url3;
                String post = HttpUtil.post(urls.get(i).getUrl() + url3, params1);

                // 添加系统用户
                Map<String, Object> owners = JSON.parseObject(post);
                List<Map> owner = JSON.parseArray(owners.get("data").toString(), Map.class);
                Map<String, Object> params2 = new HashMap<String, Object>();


                params2.put("operCd", phone);
                params2.put("email", null);
                params2.put("operNm", owner.get(0).get("ownerName"));
                params2.put("operPwd", null);
                params2.put("operSt", null);
                params2.put("telephone", phone);
                params2.put("insUuid", 1);// 暂时默认集团
                params2.put("insCd", 1);// 暂时默认集团
                params2.put("job", owner.get(0).get("workJob"));
                params2.put("ownerId", owner.get(0).get("id"));
                params2.put("ownerName", owner.get(0).get("ownerName"));
                params2.put("openId", ssoWxUser.getWeixinOpenid());
                params2.put("operSt", "0");

                params2.put("roleCd", "0".equals(role) ? urls.get(i).getOwnerNo() : urls.get(i).getEstateNo());
                String post2 = HttpUtil.post(urls.get(i).getUrl() + url2, params2);
                Map result = JSON.parseObject(post2);
                if (post2.indexOf("失败") > -1) {
                    errMsg += urls.get(i).getDescription() + "(" + result.get("msg") + ")" + ",";
                } else {
                    if (StrUtil.isBlank(binding)) {
                        binding += urls.get(i).getId();

                    } else {
                        binding += ",";
                        binding += urls.get(i).getId();
                    }
                    msg += urls.get(i).getDescription() + "(" + result.get("msg") + ")" + ",";
                }
            }
            if (StrUtil.isNotBlank(errMsg)) {
                res.put("errMsg", errMsg + "绑定失败");
            }
            if (StrUtil.isNotBlank(msg)) {

                res.put("wyUrl", urls);
                res.put("msg", msg + "绑定成功");

                if (StrUtil.isNotBlank(ssoWxUser.getRelateIds())) {
                    user.setRelateIds(ssoWxUser.getRelateIds() + "," + binding);
                } else {
                    user.setRelateIds(binding);
                }

                ssoWxUserMapper.updateSsoWxUser(user);
            }

            res.put("code", 0);
            // res.put("msg", "绑定成功");
            return res;
        }

    }

    @Override
    public boolean isBinding(Long userId, String ids) {

        SsoWxUser wxUser = ssoWxUserMapper.selectSsoWxUserById(userId);
        String relateIds = wxUser.getRelateIds();
        String[] idList = ids.split(",");

        for (String id : idList) {
            if (relateIds != null && relateIds.indexOf(id) > -1) {
                return true;
            }
        }
        return false;
    }

    @Override
    @Transactional
    public void deleteWyUrl(String userInfo, String host, String ids) {


        SsoWyUrl wyUrl = this.wyUrlMapper.selectByUrl(host);
        String ID[] = ids.split(",");
        for (String id : ID) {
            SsoWxUser wxUser = this.ssoWxUserMapper.selectSsoWxUserById(Long.parseLong(id));
            String relateIds = wxUser.getRelateIds();
            String[] relateId = relateIds.split(",");
            StringBuffer buff = new StringBuffer();
            for (String relate : relateId) {
                if (!relate.equals(wyUrl.getId())) {
                    buff.append(relate + ",");
                }
            }
            if (StrUtil.isNotBlank(buff.toString())) {
                wxUser.setRelateIds(buff.substring(0, buff.length() - 1));
            }
            this.ssoWxUserMapper.updateSsoWxUser(wxUser);


        }

    }

    @Override
    public Map<String, Object> unbundle(Long userId) {
        Map<String, Object> res = new HashMap<String, Object>();

        //物管地址
        String url1 = "/operInf/unbundle";//解绑

        //找到自己绑定的url
        SsoWxUser ssoWxUser = this.ssoWxUserMapper.selectSsoWxUserById(userId);

        String relateIds =  ssoWxUser.getRelateIds();
        StringBuffer newRelateIds = new StringBuffer();
        Map<String, Object> params = new HashMap<>();
        params.put("openId", ssoWxUser.getWeixinOpenid());

        String[] ids = relateIds.split(",");
        for (String id :
                ids) {
            SsoWyUrl ssoWyUrl = this.wyUrlMapper.selectSsoWyUrlById(Long.parseLong(id));

            String post = HttpUtil.post(ssoWyUrl.getUrl() + url1, params, 3000);
            if (StrUtil.isNotBlank(post) && !post.contains("Error")) {
                JSONObject result = JSONObject.parseObject(post);
                if (!result.get("code").equals("0")) {
                    newRelateIds.append(id);
                    newRelateIds.append(",");
                }
            }

        }

        if (newRelateIds.length() > 0 && StrUtil.isNotBlank(newRelateIds.toString())) {
            ssoWxUser.setRelateIds(newRelateIds.substring(0, newRelateIds.length() - 1));
            int result = this.ssoWxUserMapper.updateSsoWxUser(ssoWxUser);
            if (result > 0) {
                res.put("code", 1);
                res.put("msg", "解绑异常，请联系管理员");
            }

        } else {
            int result = this.ssoWxUserMapper.unbundle(userId);
            if (result > 0) {
                res.put("code", 0);
                res.put("msg", "解绑成功");

            }
        }


        return res;
    }


}
